// src/api/category.js
import api from '@/api/user' // 使用现有的api实例

// 分页查询分类（根据名称搜索）
export const findCategoryPage = (params) => {
    if (params.name) {
        // 如果有搜索条件，使用搜索接口
        return api.get('/category/searchbyname', {
            params: {
                name: params.name,
                current: params.current,
                size: params.size
            }
        }).then(response => {
            // 统一返回格式
            if (response.success) {
                return {
                    ...response,
                    data: {
                        records: Array.isArray(response.data) ? response.data : [],
                        total: response.total || (Array.isArray(response.data) ? response.data.length : 0),
                        current: params.current,
                        size: params.size
                    }
                };
            }
            return response;
        });
    } else {
        // 获取所有分类并模拟分页
        return api.get('/category')
            .then(response => {
                if (response.success) {
                    const categories = Array.isArray(response.data) ? response.data : [];
                    const start = (params.current - 1) * params.size;
                    const end = start + params.size;
                    const records = categories.slice(start, end);
                    const total = categories.length;

                    return {
                        ...response,
                        data: {
                            records,
                            total,
                            current: params.current,
                            size: params.size
                        }
                    };
                }
                return response;
            });
    }
}

// 新增分类
export const addCategory = (data) => {
    return api.post('/category/add', data)
}

// 更新分类
export const updateCategory = (data) => {
    return api.put('/category/update', data)
}

// 删除分类
export const deleteCategory = (id) => {
    return api.delete(`/category/${id}`)
}

// 获取所有分类
export const getAllCategories = () => {
    return api.get('/category')
}

export const uploadCategoryImage = (file) => {
    const formData = new FormData();
    formData.append('file', file);
    return api.post('/category/upload', formData, {
        headers: {
            'Content-Type': 'multipart/form-data'
        }
    });
}

export default {
    findCategoryPage,
    addCategory,
    updateCategory,
    deleteCategory,
    getAllCategories,
    uploadCategoryImage
}